package com.codbking.calendar.exaple.calendar;


import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

import com.codbking.calendar.exaple.R;

import java.util.Date;
import java.util.LinkedList;

public class CalendarDateView extends ViewPager {

    private static final String TAG = "CalendarDateView";
    SparseArray<CalendarView> calendarViewSparseArray = new SparseArray<>();
    private CalendarTopViewChangeListener calendarTopViewChangeListener;
    private CalendarView.OnItemClickListener onItemClickListener;
    private LinkedList<CalendarView> calendarViewList = new LinkedList<>();
    //TODO  2017/4/14
    private int row = 6;
    private CalendarAdapter calendarAdapter;
    private int calendarOpenItemHeight = 0;
    private boolean isHorizontal = false;

    public void setAdapter(CalendarAdapter calendarAdapter) {
        this.calendarAdapter = calendarAdapter;
        setCurrentItem(Integer.MAX_VALUE / 2, false);
        getAdapter().notifyDataSetChanged();
    }

    public void setOnItemClickListener(CalendarView.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public CalendarDateView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CalendarDateView);
        row = a.getInteger(R.styleable.CalendarDateView_cbd_calendar_row, 6);
        a.recycle();
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int calendarHeight = 0;
        if (getAdapter() != null) {
            CalendarView view = (CalendarView) getChildAt(0);
            if (view != null) {
                calendarHeight = view.getMeasuredHeight();
                calendarOpenItemHeight = view.getOpenItemHeight();
            }
        }
        setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(calendarHeight, MeasureSpec.EXACTLY));
    }

    private void init() {
        final int[] ymd = CalendarUtil.getYMD(new Date());
        final int[] ywd = CalendarUtil.getYWD(new Date());
        setAdapter(new PagerAdapter() {
            private boolean firstInit = true;

            @Override
            public int getCount() {
                return Integer.MAX_VALUE;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                Log.d(TAG, "setPrimaryItem position ; " + position);
                if (firstInit) {
                    initCalendarData(calendarViewSparseArray.get(position));
                    firstInit = false;
                }
                refreshLeftAndRightCalendarData();
            }

            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                Log.d(TAG, "instantiateItem position ; " + position);
                CalendarView calendarView;

                if (!calendarViewList.isEmpty()) {
                    calendarView = calendarViewList.removeFirst();
                    calendarView.setFullScreen(calendarTopViewChangeListener.isFullScreen());
                } else {
                    calendarView = new CalendarView(container.getContext(), row, calendarTopViewChangeListener.isFullScreen());
                }
                calendarView.setOnItemClickListener(onItemClickListener);
                calendarView.setAdapter(calendarAdapter);

                container.addView(calendarView);
                calendarViewSparseArray.put(position, calendarView);
                return calendarView;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                Log.d(TAG, "destroyItem position ; " + position);
                container.removeView((View) object);
                calendarViewList.addLast((CalendarView) object);
                calendarViewSparseArray.remove(position);
            }

            private void initCalendarData(CalendarView calendarView) {
                if (calendarTopViewChangeListener.isFold()) {
                    calendarView.setData(CalendarFactory.getWeekOfDayList(ywd[0], ywd[1]),
                            CalendarUtil.getYearByWeek(ywd[0], ywd[1]),
                            CalendarUtil.getMouthByWeek(ywd[0], ywd[1]),
                            ywd[1],
                            CalendarUtil.getDayByWeek(ywd[0], ywd[1]),
                            calendarTopViewChangeListener.isFullScreen());
                } else {
                    calendarView.setData(CalendarFactory.getMonthOfDayList(ymd[0], ymd[1]),
                            CalendarUtil.getYear(ymd[0], ymd[1]),
                            CalendarUtil.getMouth(ymd[0], ymd[1]),
                            CalendarUtil.getWeek(ymd[0], ymd[1], ymd[2]),
                            ymd[2],
                            calendarTopViewChangeListener.isFullScreen());
                }
            }
        });

        addOnPageChangeListener(new SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.d(TAG, " onPageScrolled " + positionOffset + " " + positionOffsetPixels);
                if (positionOffset == 0 && positionOffsetPixels == 0) {
                    isHorizontal = false;
                } else {
                    isHorizontal = true;
                }

            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.d(TAG, "onPageSelected");
                if (onItemClickListener != null) {
                    CalendarView view = calendarViewSparseArray.get(position);
                    onItemClickListener.onItemClick(view.getSelectChildView(), view.getSelectPosition(), view.getSelectCalendarInfo());
                }
                calendarTopViewChangeListener.onLayoutChange(CalendarDateView.this);
            }
        });
    }

    int[] getCurrentSelectPosition() {
        CalendarView view = calendarViewSparseArray.get(getCurrentItem());
        if (view == null) {
            view = (CalendarView) getChildAt(0);
        }
        if (view != null) {
            return view.getSelectItemRect();
        }
        return new int[4];
    }

    int getOpenItemHeight() {
        return calendarOpenItemHeight;
    }

    public boolean isHorizontal() {
        return isHorizontal;
    }

    public void setCalendarTopViewChangeListener(CalendarTopViewChangeListener listener) {
        calendarTopViewChangeListener = listener;
    }

    void viewChangeWithScrollDistance(int distance) {
        Log.d(TAG, "itemViewChangeWithScrollDistance " + calendarViewSparseArray.size());
        calendarViewSparseArray.get(getCurrentItem()).itemViewChangeWithScrollDistance(distance);
    }

    void setLeftAndRightPageScrollFullScreenType() {
        for (int i = 0; i < calendarViewSparseArray.size(); i++) {
            if (calendarViewSparseArray.valueAt(i) != null && calendarViewSparseArray.valueAt(i) != calendarViewSparseArray.get(getCurrentItem())) {
//                Log.d(TAG, "setLeftAndRightPageScrollFullScreenType position : " + calendarViewSparseArray.keyAt(i));
                CalendarView calendarView = calendarViewSparseArray.valueAt(i);
                calendarView.itemViewScrollFullScreenType();
            }
        }
    }

    void setLeftAndRightPageScrollOpenType() {
        for (int i = 0; i < calendarViewSparseArray.size(); i++) {
            if (calendarViewSparseArray.valueAt(i) != null && calendarViewSparseArray.valueAt(i) != calendarViewSparseArray.get(getCurrentItem())) {
//                Log.d(TAG, "setLeftAndRightPageScrollFullScreenType position : " + calendarViewSparseArray.keyAt(i));
                CalendarView calendarView = calendarViewSparseArray.valueAt(i);
                calendarView.itemViewScrollOpenType();
            }
        }
    }

    void refreshLeftAndRightCalendarData() {
        CalendarView previousCalendarView = calendarViewSparseArray.get(getCurrentItem() - 1);
        CalendarView currentCalendarView = calendarViewSparseArray.get(getCurrentItem());
        CalendarView nextCalendarView = calendarViewSparseArray.get(getCurrentItem() + 1);
        currentCalendarView.printDate();
        currentCalendarView.setFullScreen(calendarTopViewChangeListener.isFullScreen());
        if (previousCalendarView != null) {
            if (calendarTopViewChangeListener.isFold()) {
                previousCalendarView.setData(CalendarFactory.getWeekOfDayList(currentCalendarView.getYear(), currentCalendarView.getWeek() - 1),
                        CalendarUtil.getYearByWeek(currentCalendarView.getYear(), currentCalendarView.getWeek() - 1),
                        CalendarUtil.getMouthByWeek(currentCalendarView.getYear(), currentCalendarView.getWeek() - 1),
                        currentCalendarView.getWeek() - 1,
                        CalendarUtil.getDayByWeek(currentCalendarView.getYear(), currentCalendarView.getWeek() - 1),
                        false);
            } else {
                previousCalendarView.setData(CalendarFactory.getMonthOfDayList(currentCalendarView.getYear(), currentCalendarView.getMouth() - 1),
                        CalendarUtil.getYear(currentCalendarView.getYear(), currentCalendarView.getMouth() - 1),
                        CalendarUtil.getMouth(currentCalendarView.getYear(), currentCalendarView.getMouth() - 1),
                        CalendarUtil.getWeek(currentCalendarView.getYear(), currentCalendarView.getMouth() - 1, currentCalendarView.getDay()),
                        currentCalendarView.getDay(),
                        calendarTopViewChangeListener.isFullScreen());
            }
            previousCalendarView.printDate();
        }
        if (nextCalendarView != null) {
            if (calendarTopViewChangeListener.isFold()) {
                nextCalendarView.setData(CalendarFactory.getWeekOfDayList(currentCalendarView.getYear(), currentCalendarView.getWeek() + 1),
                        CalendarUtil.getYearByWeek(currentCalendarView.getYear(), currentCalendarView.getWeek() + 1),
                        CalendarUtil.getMouthByWeek(currentCalendarView.getYear(), currentCalendarView.getWeek() + 1),
                        currentCalendarView.getWeek() + 1,
                        CalendarUtil.getDayByWeek(currentCalendarView.getYear(), currentCalendarView.getWeek() + 1),
                        false);
            } else {
                nextCalendarView.setData(CalendarFactory.getMonthOfDayList(currentCalendarView.getYear(), currentCalendarView.getMouth() + 1),
                        CalendarUtil.getYear(currentCalendarView.getYear(), currentCalendarView.getMouth() + 1),
                        CalendarUtil.getMouth(currentCalendarView.getYear(), currentCalendarView.getMouth() + 1),
                        CalendarUtil.getWeek(currentCalendarView.getYear(), currentCalendarView.getMouth() + 1, currentCalendarView.getDay()),
                        currentCalendarView.getDay(),
                        calendarTopViewChangeListener.isFullScreen());
            }
            nextCalendarView.printDate();
        }
    }


}
